package com.ihd.ihardware.view.tzc.me.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.content.Intent;
import android.databinding.ObservableArrayList;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.ihd.ihardware.R;
import com.ihd.ihardware.databinding.ItemMemberBinding;
import com.ihd.ihardware.pojo.MembersRes;
import com.ihd.ihardware.view.tzc.me.model.MemberRepository;
import com.ihd.ihardware.view.tzc.me.view.AddMemberActivity;

import java.util.List;

import cn.wowjoy.commonlibrary.adapter.CommonAdapter;

public class MemberViewModel extends AndroidViewModel {

    private MemberRepository mMemberRepository;

    public MemberViewModel(@NonNull Application application) {
        super(application);
    }


    private ObservableArrayList<MembersRes.DataBean> mMembers = new ObservableArrayList<>();
    public CommonAdapter mMemberAdapter = new CommonAdapter<MembersRes.DataBean, ItemMemberBinding>(R.layout.item_member, mMembers, null) {
        @Override
        public void convert(ItemMemberBinding mDataBinding, MembersRes.DataBean test_concern, int position) {
            if (!TextUtils.isEmpty(test_concern.getAvatar()))
                Glide.with(mDataBinding.concernedItemLL.getContext())
                        .load(Uri.parse(test_concern.getAvatar()))
                        .apply(RequestOptions.circleCropTransform())
                        .into(mDataBinding.head);
            mDataBinding.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    delMember(test_concern.getMemberId());
                }
            });
            mDataBinding.itemLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(v.getContext(), AddMemberActivity.class);
                    i.putExtra("member", test_concern);
                    v.getContext().startActivity(i);
                }
            });
        }
    };

    public void setMembers(List<MembersRes.DataBean> list) {
        mMembers.clear();
        if (list != null && list.size() > 0)
            mMembers.addAll(list);
    }

    public void delMember(String memberId) {
        if (mMemberRepository == null)
            mMemberRepository = new MemberRepository();
        mMemberRepository.delMember(memberId);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null != mMemberRepository) {
            mMemberRepository.onDestroy();
            mMemberRepository = null;
        }
    }
}
